package game;

import game.Tile.TileColor;
import game.exceptions.GroupException;
import game.exceptions.SetException;

import java.util.Iterator;
import java.util.Vector;

/**
 * Class represents a group in the Rummikub game.
 * @author Fishman Yevgeny
 * @date Oct 25, 2009
 */
public class Group extends Set{

	private int _number; 
	
	/**
	 * Constructor to create a new Group.
	 * @param number 
	 * @param tiles - tiles the group build of. 
	 * @throws GroupException if the created Group isn't accepts the rules of the game.
	 */
	public Group(int number, Vector<Tile> tiles) throws GroupException, SetException{
		super(tiles);
		_number = number;
		Vector<TileColor> tColors = new Vector<TileColor>();
		for (Iterator<Tile> iterator = tiles.iterator(); iterator.hasNext();) {
			Tile tTile = iterator.next();
			if (tTile.getNumber() != _number) {
				throw new GroupException("Attempt to create a group of tiles with different numbers.");
			}
			if (tColors.contains(tTile.getColor())) {
				throw new GroupException("Attempt to create a group with two or more tiles with same color.");
			}
			tColors.add(tTile.getColor());
		}
	}
	
	/**
	 *	Gets the common number of the Group.  
	 * @return groups number  
	 */
	public int getNumber(){
		return _number;
	}
		
	/**
	 * Adds a tile to already existing group.
	 * @param tile - new tile to add.
	 * @throws GroupException thrown if adding this tile will harm the correctness of this group.
	 */
	@Override
	public void addTile(Tile tile) throws GroupException{
		if (tile.getNumber() != this._number) {
			throw new GroupException("Attempt to add tile with [" + tile.getNumber() + 
								     "] number to group of [" + this._number + "].");
		}
		for (Iterator<Tile> iterator = this._tiles.iterator(); iterator.hasNext();) {
			Tile tTile = iterator.next();
			if (tTile.getColor().equals(tile.getColor())) {
				throw new GroupException("Attempt to add " + tile.getColor().toString() + 
										 " tile to group where this color already exists.");
			}
		}
		
		this._tiles.add(tile);
	}
	
}
